import React, { Component } from 'react'
import { Table, Tag, Space, Drawer, Form, Input, Button, Switch, message, Spin, notification, Modal } from 'antd'
import { requestGetUserlist, requestModifyUserlist, requestRemoveUserlist } from '../../api/user'
import * as PropTypes from 'prop-types'
import { SearchOutlined } from '@ant-design/icons'
import QueueAnim from 'rc-queue-anim'
import { connect } from 'react-redux'
import UserBuy from './chart/Buy'

function Highlighter (props) {
    return null
}

Highlighter.propTypes = {
    highlightStyle: PropTypes.shape({ padding: PropTypes.number, backgroundColor: PropTypes.string }),
    textToHighlight: PropTypes.any,
    autoEscape: PropTypes.bool,
    searchWords: PropTypes.arrayOf(PropTypes.string)
}

export class Customer extends Component {
    state = {
        dataList: [],
        loading: true,
        editVisible: false,
        isModalVisible: false,
        userid: '',
        mode: 'edit',
        tableHeight: window.innerHeight - 320,
        formRef: null,
        _id: null,
        searchText: '',
        searchedColumn: '',
        show: true
    }

    componentDidMount () {
        this.init()
        if (!localStorage.getItem('userNotify')) {
            const key = `open${Date.now()}`
            notification.info({
                message: '使用提示',
                description: '点击表头放大镜图标可以进行用户查询，支持模糊查询',
                duration: null,
                // eslint-disable-next-line
                btn: <a onClick={() => {
                    notification.close(key)
                    localStorage.setItem('userNotify', true)
                }}>不再提示</a>,
                key
            })
        }
    }

    init () {
        requestGetUserlist().then(res => {
            this.setState({
                dataList: res.data,
                loading: false
            })
        })
    }

    edit (record) {
        this.setState({
            editVisible: true,
            mode: 'edit',
            formRef: React.createRef(),
            _id: record._id
        }, () => {
            setTimeout(() => {
                this.state.formRef.current.setFieldsValue(record)
            }, 100)
        })
    }

    add () {
        this.setState({
            editVisible: true,
            mode: 'add',
            formRef: React.createRef()
        })
    }

    copyWhenClick (text) {
        const copyer = document.getElementById('copy')
        copyer.value = text
        copyer.select()
        document.execCommand('copy')
        // message.success('复制userid成功！')
        this.setState({
            userid: text,
            isModalVisible: true
        })
    }

    getColumnSearchProps = (dataIndex, placeholder) => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <div style={{ padding: 8 }}>
                <Input
                    ref={node => {
                        this.searchInput = node
                    }}
                    placeholder={placeholder ? placeholder : `Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{ marginBottom: 8, display: 'block' }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<SearchOutlined/>}
                        size="small"
                    >
                        搜索
                    </Button>
                    <Button onClick={() => this.handleReset(clearFilters, confirm)} size="small">
                        重置
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }}/>,
        onFilter: (value, record) =>
            record[dataIndex]
                ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()) || (record['userid'] && record['userid'].toString().includes(value))
                : '',
        onFilterDropdownVisibleChange: visible => {
            if (visible) {
                setTimeout(() => this.searchInput.select(), 100)
            } else {
                this.setState({ searchText: '' })
            }
        },
        render: text =>
            this.state.searchedColumn === dataIndex ? (
                <Highlighter
                    highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                    searchWords={[this.state.searchText]}
                    autoEscape
                    textToHighlight={text ? text.toString() : ''}
                />
            ) : (
                text
            ),
    })

    handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm()
        this.setState({
            searchText: selectedKeys[0],
            searchedColumn: dataIndex,
        })
    }

    handleReset = (clearFilters, confirm) => {
        clearFilters()
        confirm({ closeDropdown: true })
        this.setState({ searchText: '' })
    }

    onClose () {
        this.setState({
            editVisible: false
        })
        this.state.formRef.current.resetFields()
    }

    handleCancel () {
        this.setState({
            isModalVisible: false
        })
    }

    onFinish (values) {
        let { mode, _id } = this.state
        switch (mode) {
            case 'edit':
                requestModifyUserlist(_id, values).then(res => {
                    message.success(res.msg)
                    this.init()
                })
                console.log('edit', _id, values)
                break
            case 'add':
                console.log('add', values)
                break
            default:
                console.log('暂时没有这个策略')
        }
    }

    delete (id) {
        requestRemoveUserlist(id).then(res => {
            console.log(res)
            message.success(res.msg)
            this.init()
        })
    }

    render () {
        const columns = [
            {
                title: '用户名',
                dataIndex: 'username',
                key: 'username',
                ...this.getColumnSearchProps('username', '请输入id或用户名'),
                // eslint-disable-next-line
                render: (text, record) => <a onClick={this.copyWhenClick.bind(this, record.userid)}>{text}</a>,
            },
            {
                title: '密码',
                dataIndex: 'password',
                key: 'password',
                render: () => <label>******</label>
            },
            {
                title: '类型',
                key: 'tags',
                render: () => (
                    <Tag color="gold">
                        普通用户
                    </Tag>
                ),
            },
            {
                title: '状态',
                key: 'freeze',
                dataIndex: 'freeze',
                render: (text) => (
                    text ? (<Tag color="red">
                        冻结
                    </Tag>) : (<Tag color="green">
                        正常
                    </Tag>)
                ),
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => (
                    <Space size="middle">
                        {/*eslint-disable-next-line*/}
                        <a onClick={this.edit.bind(this, record)}>编辑</a>
                        {/*<Popconfirm onConfirm={this.delete.bind(this, record._id)} title="确认删除？">*/}
                        {/*    /!*eslint-disable-next-line*!/*/}
                        {/*    <a style={{ color: '#FF4D4F' }}>注销</a>*/}
                        {/*</Popconfirm>*/}
                    </Space>
                ),
            },
        ]
        let element = null
        if (this.state.loading) {
            element = (<div className="loading">
                <Spin tip="Loading..." spinning={this.state.loading} size="large"/>
            </div>)
        } else {
            element = (<>
                <Table style={{ width: '100%' }} scroll={{ y: this.state.tableHeight }} className="userTable"
                       dataSource={this.state.dataList}
                       columns={columns} rowKey={record => record.userid}/>
                <Modal title="用户购买统计" visible={this.state.isModalVisible} onCancel={this.handleCancel.bind(this)}
                       width={800} footer={null}>
                    <UserBuy userid={this.state.userid}></UserBuy>
                </Modal>

                <Drawer width={500} visible={this.state.editVisible} title="添加/编辑" placement="right"
                        onClose={this.onClose.bind(this)} footer={null}>
                    <Form
                        name="basic"
                        labelCol={{ span: 4 }}
                        initialValues={{ remember: true }}
                        onFinish={this.onFinish.bind(this)}
                        autoComplete="off"
                        ref={this.state.formRef}
                    >
                        {/*<Form.Item*/}
                        {/*    label="用户名"*/}
                        {/*    name="username"*/}
                        {/*    rules={[{ required: true, message: '请输入用户名' }]}*/}
                        {/*>*/}
                        {/*    <Input/>*/}
                        {/*</Form.Item>*/}

                        {/*<Form.Item*/}
                        {/*    label="密码"*/}
                        {/*    name="password"*/}
                        {/*    rules={[{ required: true, message: '请输入密码' }]}*/}
                        {/*>*/}
                        {/*    <Input/>*/}
                        {/*</Form.Item>*/}
                        <Form.Item
                            label="冻结"
                            name="freeze"
                            valuePropName="checked"
                            initialValue={false}
                        >
                            <Switch/>
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                            <Space>
                                <Button type="primary" htmlType="submit">提交</Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Drawer>
            </>)
        }
        return (<QueueAnim className="demo-content" key="demo">
            {this.props.show ? <div className="demo-tbody" key="a">{element}</div> : null}
        </QueueAnim>)
    }
}

export default connect((state) => {
    return {
        show: state.getIn(['fade', 'show'])
    }
})(Customer)
